package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.health.dao.PermissionDao;
import com.itheima.health.dao.RoleDao;
import com.itheima.health.dao.UserDao;
import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @author ：seanyang
 * @date ：Created in 2019/6/7
 * @description ：
 * @version: 1.0
 */
@Service(interfaceClass = UserService.class)
@Slf4j
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao userDao;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private PermissionDao permissionDao;

	@Override
	public boolean login(String username, String password) {
		log.debug("service_provide...u:{},p:{}",username,password);
		if("admin".equals(username) && "123".equals(password)){
			return true;
		}
		return false;
	}

	@Override
	public User findByUsername(String username) {
		log.debug("service_provide...从数据库读取用户信息:{}",username);
		// 从数据库读取用户信息
		User user = userDao.findByUsername(username);
		if (user == null){
			return null;
		}
		// 获取角色列表
		Set<Role> roles = roleDao.findByUserId(user.getId());
		for (Role role:roles){
			Integer roleId = role.getId();
			// 获取权限列表
			Set<Permission> permissions = permissionDao.findByRoleId(roleId);
			if(permissions!=null && permissions.size() > 0){
				// 把权限列表添加到当前角色
				role.setPermissions(permissions);
			}
		}
		// 把当前角色集合添加到当前用户
		user.setRoles(roles);
		log.debug("findByUsername:{}",user);
		return user;
	}
}
